using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using WareForms;
using Hydrobase;
using HydrobaseSDK;
using TheDarkOwlLogger;
using wow_backitupSDK;

namespace wow_backtiupCore
{
    /// <summary>
    /// The Core(main and the brain of this project  )  class of this library, handles backup, 
    /// restore of this project 
    /// </summary>
    public class Kernel
    {

        public const string buildCode = "Alexstrasza";
        /// <summary>
        /// The static instance of thr progress dialog  showing progress of  your 
        /// preferences backing up.
        /// </summary>
       public  static frmProgress  WTFprog = new frmProgress();
        /// <summary>
       /// The static instance of thr progress dialog  showing progress of  your 
       /// addons backing up.
        /// </summary>
        public static frmProgress IntProg = new frmProgress();
        /// <summary>
        /// Constant for the wtf folder (the folder that holds your prefereces in wow)
        /// </summary>
        public const string WTfFolder = "WTF";
        /// <summary>
        /// Constant for the wow folder (where wow is installed)
        /// </summary>
        public const string WoWFolder = "World of Warcraft";
        /// <summary>
        /// Constant for the interface folder (the folder that holds your addons in wow)
        /// </summary>
        public const string InterfaceFolder = "Interface";
        /// <summary>
        /// Text that will be added in the start of every  backup archive for preferences folder
        /// </summary>
        public const string WtfBackup = "WTF-backup-";
        /// <summary>
        /// Text that will be added in the start of every  backup archive for addons folder
        /// </summary>
        public const string InterfaceBackup = "Interface-backup-";
        /// <summary>
        /// Const that has the fiel extension of the archives
        /// 
        /// </summary>
        public const string ArchExtension = ".zip";
        /// <summary>
        /// constant of wow' config file 
        /// </summary>
        public const string WoWConfigFile = "Config.wtf";
        
        internal  static  Process pros;
        /// <summary>
        /// Cells of application config file
        /// </summary>
        public static string[] Appinfocells = {  "Name",  "Path", "Comment" };
        DataTable appinftable;
        /// <summary>
        /// Toolbar of external applications
        /// </summary>
        internal static ToolStrip ExernalAppToolbar;
        /// <summary>
        /// Static instance of external application menu
        /// </summary>
        internal static ToolStripMenuItem  ExernalAppMenu;
       
       
        string givenwowfolder;
        DateTime time = DateTime.Now;
        //FastZipEvents FastZipEven = new FastZipEvents();
        FastZip zipBackHudlerCompr, zipBackHudlerRest;
        FastZip zipWTFHundlerCompr, zipWTFHundlerRest;
        /// <summary>
        /// returns the version of  WowBackitup Core
        /// </summary>
        /// <returns>returns the version of  WowBackitup Core</returns>
        public static  string GetVersion()
        {
            try
            {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString()+"( " + buildCode + " )";


            }

            catch (Exception ex)
            {
                return Application.ProductVersion;

                Program.Bugtracking(ex);
            }


        }
        /// <summary>
        /// Backips the addons of the given world of warcraft's  folder to the target folder        
        /// </summary>
        /// <param name="wowfolder"> the path of world of warcraft installation 
        ///  <b>Note</b> Don't include the interface or addons folder. only the path of wow installation.
        /// <example> if wow is installed in Program files you should put.
        ///  C:\Program files\World of Warcraft   </example>
        /// </param>
        /// <param name="targetbackupfolder">path of the backup folder.
        /// <b>Note</b> You cant change te name of the backup file.
        /// you should put only  folder as value . The ptarget folder must exist</param>
        public void BackupInterface(string wowfolder,string targetbackupfolder)
        {
            try
            {
                
                
                if ((wowfolder != null) || (targetbackupfolder != null) )
                {
                  //  this.CurAction = enumActioncs.Backup;

                    FastZipEvents bakenebts= new FastZipEvents();
                    bakenebts.Progress += new ProgressHandler(this.ProgressInt);
                 // bakenebts.ProcessFile += new ProcessFileHandler(this.bakProcessfileInt );
                    zipBackHudlerCompr = new FastZip(bakenebts);

                    string tmpfilename = InterfaceBackup +" "+ time.ToShortDateString() + " - " + time.ToShortTimeString();
                    string filename = tmpfilename.Replace("/", "-"); 
                    filename = filename.Replace(":", "_");
                    IntProg = new frmProgress();
                    IntProg.Text = "Interface Folder Progress:";
                    IntProg.Show();
                    zipBackHudlerCompr.CreateEmptyDirectories = true;
                    zipBackHudlerCompr.CreateZip(targetbackupfolder + "\\" + filename + ArchExtension, wowfolder + "\\" + InterfaceFolder, true, "");
                   
                    
                    



                }


                

            }
            catch (Exception ex)
            {


                Program.Bugtracking(ex);
                
            }




        }
        /// <summary>
        /// Backips the wow's preferences (wtf folder) of the given world of warcraft's  folder to the target folder
        /// </summary>
        /// <param name="wowfolder">the path of world of warcraft installation 
        ///  <b>Note</b> Don't include the wtf  folder. only the path of wow installation.
        /// <example> if wow is installed in Program files you should put.
        ///  C:\Program files\World of Warcraft   </example></param>
        /// <param name="targetbackupfolder">path of the backup folder.
        /// <b>Note</b> You cant change te name of the backup file.
        /// you should put only  folder as value . The ptarget folder must exist</param>
        public void BackupWTF(string wowfolder, string targetbackupfolder)
        {
            try
            {
                
                if ((wowfolder != null) || (targetbackupfolder != null))
                {
                  //  this.CurAction = enumActioncs.Backup;
                    FastZipEvents even = new FastZipEvents();
                even.Progress += new ProgressHandler(this.ProgressWTF);
                  //even.ProcessFile+= new ProcessFileHandler(this.bakProcessfilewtf);
                zipWTFHundlerCompr = new FastZip(even);
                    string merawra=time.ToShortDateString() + " - " + time.ToShortTimeString();
                    givenwowfolder = wowfolder;
                    string tmpfilename = WtfBackup +merawra  ;
                    string filename = tmpfilename.Replace("/", "-");
                    filename = filename.Replace(":", "_");
                    WTFprog = new frmProgress();
                    WTFprog.Text = "WTF Folder Progress:";
                    WTFprog.Show();
                    zipWTFHundlerCompr.CreateEmptyDirectories = true;
                    zipWTFHundlerCompr.CreateZip(targetbackupfolder + "\\" + filename + ArchExtension, wowfolder + "\\" + WTfFolder + "\\", true, "");

                    




                }
               


            }
            catch (Exception ex)
            {


                Program.Bugtracking(ex);
             

            }




        }
        /// <summary>
        /// this event handler shows backup's progress of wtf folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
      public    void ProgressWTF(Object sender,	ProgressEventArgs e)
          {

              try
              {
                  
                      if (e.Name.Contains(WTfFolder) == true)
                      {
                          WTFprog.lblFileName.Text = e.Name;
                          WTFprog.progressBar.Value = Convert.ToInt32(e.PercentComplete);
                          WTFprog.Refresh();



                      }
                      else
                      {

                          WTFprog.Close();

                      }
                    
                  

              }
              catch(Exception ex)
              {
                  Program.Bugtracking(ex);

              }

          }
     /// <summary>
      /// this event handler shows backup's progress of addons folder
     /// </summary>
     /// <param name="sender"></param>
     /// <param name="e"></param>
      public   void ProgressInt(Object sender, ProgressEventArgs e)
        {

            try
            {

               

                    if (e.Name.Contains(InterfaceFolder) == true)
                    {
                        IntProg.lblFileName.Text = e.Name;
                        IntProg.progressBar.Value = Convert.ToInt32(e.PercentComplete);
                        IntProg.Refresh();
                        
                    }
                    else
                    {
                        IntProg.Close();
                    }
               
                
            }
            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }

        }
      /// <summary>
      /// Restores the normal filename of the wow main config file after the backup
      /// </summary>
        public void RestoreOriginalFileNameAfterBackup()
        {

            try
            {
                if (this.givenwowfolder != null)
                {

                    File.Move(givenwowfolder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + Environment.MachineName, givenwowfolder + "\\" + WTfFolder + "\\" + WoWConfigFile);


                }



            }
            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }


        }
        /// <summary>
        /// changes the original file name of main config file before it back it up.
        /// </summary>
        /// <param name="twowfolder">the path of world of warcraft installation 
        ///  <b>Note</b> Don't include the wtf  folder. only the path of wow installation.
        /// <example> if wow is installed in Program files you should put.
        ///  C:\Program files\World of Warcraft   </example></param>
        public void ChangeOriginalFileNameBeforeBackup(string twowfolder)
        {

            try
            {
                if ((twowfolder != null) &&(File.Exists(twowfolder + "\\" + WTfFolder + "\\" + WoWConfigFile)==true))
                {

                    File.Move(twowfolder + "\\" + WTfFolder + "\\" + WoWConfigFile, twowfolder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + Environment.MachineName);


                }



            }
            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }


        }
        /// <summary>
        /// Restores the wtf folder to the wow installation
        /// </summary>
        /// <param name="filename">the file of the backup archive you want to recover</param>
        /// <param name="wowfolder">the path of world of warcraft installation 
        ///  <b>Note</b> Don't include the wtf  folder. only the path of wow installation.
        /// <example> if wow is installed in Program files you should put.
        ///  C:\Program files\World of Warcraft   </example></param>
        public void RestoreWTF(string filename, string wowfolder)
        {
            try
            {
                if ((filename != null) || (File.Exists(filename) == true) || (wowfolder != null))
                {
                    //this.CurAction = enumActioncs.Restore;
                    FastZipEvents even = new FastZipEvents();
                    even.Progress += new ProgressHandler(this.ProgressWTF);
                  //  even.ProcessFile += new ProcessFileHandler(this.restProcessfilewtf);
                    
                    zipWTFHundlerRest = new FastZip(even );
                    WTFprog = new frmProgress();
                    WTFprog.Text = "WTF Folder Progress:";
                    WTFprog.Show();
                    zipWTFHundlerRest.ExtractZip(filename, wowfolder + "\\" + WTfFolder, "");
                    

                }

            }
            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }
           


        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="wowfolder">the path of world of warcraft installation 
        ///  <b>Note</b> Don't include the wtf  folder. only the path of wow installation.
        /// <example> if wow is installed in Program files you should put.
        ///  C:\Program files\World of Warcraft   </example></param>
        public void RestoreInterface(string filename, string wowfolder)
        {
            try
            {
                if ((filename != null) || (File.Exists(filename) == true) || (wowfolder != null))
                {
                    //this.CurAction = enumActioncs.Restore;
                    FastZipEvents even = new FastZipEvents();
                    even.Progress += new ProgressHandler(this.ProgressInt);
                    //even.ProcessFile += new ProcessFileHandler(this.restProcessfileInt);
                    this.zipBackHudlerRest = new FastZip(even);
                    IntProg = new frmProgress();
                    IntProg.Text = "Interface Folder Progress:";
                    IntProg.Show();
                    this.zipBackHudlerRest.ExtractZip(filename, wowfolder + "\\" + InterfaceFolder, "");
                    
                 
                    
                }

            }
            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }



        }
        /// <summary>
        /// Changes the original main wow's options file before restores
        /// </summary>
        /// <param name="machinename">the name of your machine(pc)</param>
        /// <param name="twowflder">the path of world of warcraft installation 
        ///  <b>Note</b> Don't include the wtf  folder. only the path of wow installation.
        /// <example> if wow is installed in Program files you should put.
        ///  C:\Program files\World of Warcraft   </example></param>
        public void ChangeOriginalFilenameBeforeRestore(string machinename, string twowflder)
        {
            try
            {/* 
             
              */
                if (twowflder != null)
                {

                  
                    if ((machinename != null) && (machinename != "-"))
                    {
                        
                        if (File.Exists(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile) == true)
                        {
                            Random rnd = new Random();
                            File.Move(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile, twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile+ "."+machinename.ToUpperInvariant() );



                        }
                        else if (File.Exists(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + machinename.ToUpperInvariant()) == true)
                        {
                            Random rnd = new Random();
                            File.Move(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + machinename, twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + machinename.ToUpperInvariant() + ".bak." + Convert.ToString(rnd.Next()));


                        }


                    }
                    else
                    {
                        if (File.Exists(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile) == true)
                        {
                            Random rnd = new Random();
                            File.Move(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile, twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile+ Environment.MachineName);



                        }
                        else if (File.Exists(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + Environment.MachineName) == true)
                        {
                            Random rnd = new Random();
                            File.Move(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + Environment.MachineName, twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + Environment.MachineName + ".bak." + Convert.ToString(rnd.Next()));


                        }
                    }








                }
               



            }
            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }


        }
        /// <summary>
        /// changes back to the original the name of main options file after restore
        /// </summary>
        /// <param name="machinename">the name of your machine (pc) </param>
        /// <param name="twowflder">the path of world of warcraft installation 
        ///  <b>Note</b> Don't include the wtf  folder. only the path of wow installation.
        /// <example> if wow is installed in Program files you should put.
        ///  C:\Program files\World of Warcraft   </example></param>
        public void ChangeOriginalFilenameAfterRestore(string machinename,string twowflder)
        {
            try
            {
                if (twowflder != null)
                {
                    if ((machinename != null) && (machinename != "-"))
                    {
                    
                        if (File.Exists(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile ) == true)
                        {

                            if (File.Exists(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile) == true)
                            {
                                Random rnd = new Random();
                                File.Move(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile, twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile+ "."+machinename.ToUpperInvariant()+".bak");



                            }
                            else  if (File.Exists(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + machinename.ToUpperInvariant()+".bak") == true)
                            {
                                Random rnd = new Random();
                                File.Move(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + machinename.ToUpperInvariant(), twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + machinename.ToUpperInvariant() + ".bak." + Convert.ToString(rnd.Next()));


                            }
                            File.Move(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + machinename.ToUpperInvariant(), twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile);


                        }
                        else
                        {

                            if (File.Exists(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + Environment.MachineName) == true)
                            {





                                File.Move(twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile + "." + Environment.MachineName, twowflder + "\\" + WTfFolder + "\\" + WoWConfigFile);


                            }
                            else
                            {

                                MessageBox.Show("Go to " + twowflder + "\\" + WTfFolder + " and Rename manualy the File \n" + WoWConfigFile + " the name of ur pc  to be " + WoWConfigFile);
 


                            }

                        }
                    
                        

                    }


                }


            }
            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }

        }
        /// <summary>
        /// Executes the external apps from the given datatable
        /// </summary>
        /// <param name="datatble">datatable object that includes the info of external apps</param>
        public void ExecuteExternalApps(DataTable datatble)
        {
            try
            {
                if (datatble != null)
                {
                    foreach (DataRow row in datatble.Rows)
                    {
                        object[] rows = row.ItemArray;
                        if ((Convert.ToString(row[1]) != null) && (row[1] != null) && (File.Exists(Convert.ToString(row[1])) == true))
                        {
                            
                        Process.Start(Convert.ToString(row[1]));
                        }
                       

                    }

                }
            }
            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }


        }
        /// <summary>
        /// Adds the gexternal apps to the toolbar and menu
        /// </summary>
        /// <param name="tollbar">toolstrip to be added</param>
        /// <param name="table">datatable that holds info about external apps</param>
        /// <param name="menu">toolstripmenuitem that external apps will be added</param>
        public void AddExteranlAppToold(ToolStrip tollbar, DataTable table,ToolStripMenuItem  menu)
        {
          try
            {
                if ((table != null) ||(menu !=null)||(tollbar !=null))
                {
                     
                   // MessageBox.Show(table.TableName);
                    appinftable = table;
                    tollbar.Items.Clear();
                    foreach (DataRow row in table.Rows)
                    {
                        object[] rows = row.ItemArray;
                        if ((Convert.ToString(rows[1]) != null) && (row[1] != null) && (rows[0] != null) &&(Convert.ToString(rows[1])!=" ")
                            && (row[0] != DBNull.Value) && (row[1] != DBNull.Value) && (row.IsNull(0) != true) && (row.IsNull(1) != true))
                        {
                           ToolStripItem tolitem = tollbar.Items.Add(Convert.ToString(rows[0]));
                            tollbar.Tag = Convert.ToString(rows[1]);
                            menu.DropDownItems.Add(tolitem);
                            menu.DropDownItemClicked += new ToolStripItemClickedEventHandler(this.itemclickedeventmenu);
                            ExernalAppMenu = menu;
                         tollbar.Items.Add(Convert.ToString(rows[0]));
                      //  MessageBox.Show(tollbar.Items[Convert.ToString(rows[0])].Name );
                            ToolStripItem tlbitm = tollbar.Items[Convert.ToString(rows[0])];

                            tollbar.Items[Convert.ToString(rows[0])].Click += delegate(object o, EventArgs e)
                            {


                               

                                ExternalRuningProcces runingprcFinder = new ExternalRuningProcces();
                                // MessageBox.Show(Path.GetFileName(Convert.ToString(vals[1])));

                                if (Path.GetExtension(Convert.ToString(rows[1])) != ".appref-ms")
                                {


                                    Process pros = Process.Start(Convert.ToString(rows[1]));

                                    //pros.Exited += new EventHandler(runingprcFinder.prosexit);
                                    if (pros != null)
                                    {
                                        //Assembly.LoadFile(pros.StartInfo.FileName);
                                        foreach (Process p in Process.GetProcessesByName(pros.ProcessName))
                                        {
                                            if (p.Id != pros.Id)
                                            {
                                                p.Kill();
                                            }
                                        }
                                    }
                                }






                            };
                           
                         //  MessageBox.Show(Convert.ToString(row.ItemArray[1]));


                            ExernalAppToolbar = tollbar;
                    tollbar.ItemClicked += new ToolStripItemClickedEventHandler(this.itemclickedeventtoolbar);

                    ExernalAppToolbar.ItemClicked += new ToolStripItemClickedEventHandler(this.itemclickedeventtoolbar);
                        }


                    }

                }
            }
           catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }


        }
        /// <summary>
        /// The click event handler of the toolstripitem that belongs to the external application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        public void itemclickedeventmenu(object sender ,ToolStripItemClickedEventArgs  ev)
        {

            try
            {
                hydrobaseADO ado = new hydrobaseADO();
                if (appinftable != null)
                {
                    //MessageBox.Show(ev.ClickedItem.Text );
                    if (ev.ClickedItem.Text != null)
                    {
                        DataRowCollection rowcol = appinftable.Rows;
                            //ado.Search2(appinftable.DataSet, Appinfocells[0], ev.ClickedItem.Text, appinftable.TableName, appinftable.DataSet.Tables.IndexOf(appinftable));
                        if (rowcol != null) 
                        {
                            object[] vals = rowcol[ExernalAppMenu.DropDownItems.IndexOf(ev.ClickedItem)].ItemArray;
                           // vals[1] = ev.ClickedItem.Tag;
                            if ((Convert.ToString(vals[1]) != null) &&(File.Exists(Convert.ToString(vals[1]))==true ))
                            {


                                ExternalRuningProcces runingprcFinder = new ExternalRuningProcces();
                               // MessageBox.Show(Path.GetFileName(Convert.ToString(vals[1])));

                                if (Path.GetExtension(Convert.ToString(vals[1])) != ".appref-ms")
                                {


                                    Process pros = Process.Start(Convert.ToString(vals[1]));

                                    //pros.Exited += new EventHandler(runingprcFinder.prosexit);
                                    if (pros != null)
                                    {
                                        //Assembly.LoadFile(pros.StartInfo.FileName);
                                        foreach (Process p in Process.GetProcessesByName(pros.ProcessName))
                                        {
                                            if (p.Id != pros.Id)
                                            {
                                                p.Kill();
                                            }
                                        }
                                    }
                                }
                                
                                }
                              
                               
                                
                                
                              
                                   
                                
                               
                              
                                

                                
                            


                        }
                    }


                }
            }


            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }

        }
        /// <summary>
        /// The click event handler of the toolstripitem that belongs to the external application
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        public void itemclickedeventtoolbar(object sender, ToolStripItemClickedEventArgs ev)
        {

          try
            {
                hydrobaseADO ado = new hydrobaseADO();
              if (appinftable != null)
                {
              //   MessageBox.Show(ev.ClickedItem.Text );
                    if (ev.ClickedItem.Text != null)
                    {
                        DataRowCollection rowcol = appinftable.Rows;
                        //ado.Search2(appinftable.DataSet, Appinfocells[0], ev.ClickedItem.Text, appinftable.TableName, appinftable.DataSet.Tables.IndexOf(appinftable));
                        if (rowcol != null)
                        {
                            object[] vals = rowcol[ExernalAppToolbar.Items.IndexOf(ev.ClickedItem)].ItemArray;
                            // vals[1] = ev.ClickedItem.Tag;
                            if ((Convert.ToString(vals[1]) != null) || (File.Exists(Convert.ToString(vals[1])) == true))
                            {
                                

                                ExternalRuningProcces runingprcFinder = new ExternalRuningProcces();
                                // MessageBox.Show(Path.GetFileName(Convert.ToString(vals[1])));

                                if (Path.GetExtension(Convert.ToString(vals[1])) != ".appref-ms")
                                {

                                    
                                    Process pros = Process.Start(Convert.ToString(vals[1]));

                                    //pros.Exited += new EventHandler(runingprcFinder.prosexit);
                                    if (pros != null)
                                    {
                                        //Assembly.LoadFile(pros.StartInfo.FileName);
                                        foreach (Process p in Process.GetProcessesByName(pros.ProcessName))
                                        {
                                            if (p.Id != pros.Id)
                                            {
                                                p.Kill();
                                            }
                                        }
                                    }
                                }

                            }















                        }
                    }


                }
            }


            catch (Exception ex)
            {
                Program.Bugtracking(ex);

            }

        }
        
        


    }
}
